#!/usr/bin/env bash
#
# Copyright (C) 2023 Bacula Systems SA
# License: BSD 2-Clause; see file LICENSE-FOSS
#
#
# Test the BSR cycle detection and split code
# I run 4 jobs and I try to split the work on 4 volumes, this way
# 
# 1 TestVolume001
# ---- split ----
# 2 TestVolume002
# 2 TestVolume001  <== reuse TestVolume001 then split at begining of job2
# 3 TestVolume001
# ---- split ----
# 4 TestVolume003
# 4 TestVolume001  <== reuse TestVolume001 (used by job3) then cannot
#                      follow job3 and split at begining of job4
#
# I check that TestVolume001 is loaded 3 times by the restore
#

TestName="bsr-cycle1-test"
JobName=backup
. scripts/functions

scripts/cleanup
scripts/copy-test-confs
echo "${cwd}/build" >${cwd}/tmp/file-list

rm -f $cwd/build/big

start_test

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log1.out
setdebug level=4 storage=File
setdebug level=1 client
label storage=File volume=TestVolume001
run job=Simple yes
wait
label storage=File volume=TestVolume002
update Volume=TestVolume002 MaxVolBytes=128000
update volume=TestVolume001 VolStatus=Used
@exec "touch $cwd/build/po/fr.po"
run job=Simple yes
@sleep 5
update volume=TestVolume001 VolStatus=Append
mount storage=File
wait
messages
@exec "touch $cwd/build/po/es.po"
run job=Simple yes
wait
messages
label storage=File volume=TestVolume003
update Volume=TestVolume003 MaxVolBytes=128000
update volume=TestVolume001 VolStatus=Used
@exec wait=0 cmd="dd if=/dev/urandom of=$cwd/build/big bs=1M count=1"
run job=Simple yes
@sleep 5
update volume=TestVolume001 VolStatus=Append
mount storage=File
wait
message

sql
select * from jobmedia;

@# 
@# now do a restore
@#
@$out $tmp/log2.out  
setdebug level=4 storage=File
@# use dir level=20 to get the detail of the split of the BSR
@# use dir level=100 to get all the detail of the split including the BSR itself
setdebug level=100 dir
restore where=$tmp/bacula-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File
stop_bacula
check_two_logs

rm -f $cwd/build/big
count=`grep 'Ready to read from volume "TestVolume001"' $tmp/log2.out | wc -l`
expected="3"
if [ $count != $expected ] ; then
   print_debug "expect to mount TestVolume001 $expected at restore time (got $count)"
   estat=1
fi
end_test

